import threading
import queue
import time
from .LoadBalancer import balancer
from src import consumers_num,IOC_opr,parse_udp_packet,IOC_init

class Consumer:
    def __init__(self, consumer_id, balancer):
        self.id = consumer_id
        self.balancer = balancer
        self.queue = queue.Queue()
        # 启动消费者工作线程
        self.thread = threading.Thread(name="Queue 消费者"+str(consumer_id),target=self._process_messages, daemon=True)
        self.thread.start()

    def _process_messages(self):
        """持续处理消息的循环"""
        while True:
            try:
                message = self.queue.get()
                # print(f"消费者 {self.id} 开始处理消息: {message}")
                if message["from"] == "IOC—init":
                    thread = threading.Thread(name="IOC_init", target=IOC_init, args=(message["Driver"],), daemon=True)
                    thread.start()
                elif message["from"] == "IOC":
                    thread = threading.Thread(name="IOC_opr", target=IOC_opr, args=(message["pvname"], message["value"]), daemon=True)
                    thread.start()
                elif message["from"] == "UDP":
                    thread = threading.Thread(name="UDP_opr", target=parse_udp_packet, args=(message["host"], message["data"]), daemon=True)
                    thread.start()
                # 通知负载均衡器任务完成
                self.balancer.notify_task_completed(self.id)
                self.queue.task_done()
            except KeyError as e:
                print(f"错误: 消息格式错误, 错误信息: {e}")
            except Exception as e:
                print(f"错误: 处理消息失败, 消费者ID: {self.id}, 错误信息: {e}")




consumers = [Consumer(i+1, balancer) for i in range(consumers_num)]
for c in consumers:
    balancer.register_consumer(c)
    
# # 使用示例
# if __name__ == "__main__":
#     # 初始化负载均衡器
#     balancer = LoadBalancer()

#     # 创建并注册消费者
#     consumers = [Consumer(i+1, balancer) for i in range(3)]
#     for c in consumers:
#         balancer.register_consumer(c)

#     # 模拟生产者发送消息
#     for i in range(10):
#         message = f"任务-{i+1}"
#         print(f"\n生产者发送: {message}")
#         balancer.send_message(message)
#         time.sleep(0.3)  # 模拟消息生产间隔

